<?php

namespace app\shopapi\controller\user;

use app\shopapi\controller\Controller;
use app\shopapi\model\Express as ExpressModel;
use app\shopapi\model\OrderGoods as OrderGoodsModel;
use app\shopapi\model\OrderRefund as OrderRefundModel;
use think\Db;
/**
 * 订单售后服务
 * Class service
 * @package app\api\controller\user\order
 */
class Refund extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 用户售后单列表
     * @param int $state
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($state = -1)
    {
        $model = new OrderRefundModel;
        $list = $model->getList($this->user['user_id'], (int)$state);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 申请售后
     * @param $order_goods_id
     * @return array
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    // public function apply($order_goods_id)
    // {
    //     // 订单商品详情
    //     $model = new OrderRefundModel;
    //     $goods = OrderGoodsModel::detail($order_goods_id);
    //     if (isset($goods['refund']) && !empty($goods['refund'])) {
    //         // if ($goods['refund']['order_refund_id']) {
    //         //     $model->where("order_refund_id",$goods['refund']['order_refund_id'])->update(['status'=>0]);
    //         // }
    //         // return $this->renderSuccess([], '提交成功');
    //         return $this->renderError('已申请过售后');
    //     }
    //     if (!$this->request->isPost()) {
    //         return $this->renderSuccess(['detail' => $goods]);
    //     }
    //     // 新增售后单记录
    //     if ($model->apply($this->user, $goods, $this->request->post())) {
    //         return $this->renderSuccess([], '提交成功');
    //     }
    //     return $this->renderError($model->getError() ?: '提交失败');
    // }
    public function apply($order_goods_id)
    {
        // 订单商品详情
        $model = new OrderRefundModel;
        $goods = OrderGoodsModel::detail($order_goods_id);

        if (!$this->request->isPost()) {
            return $this->renderSuccess(['detail' => $goods]);
        }

        // 本次提交的参数
        $post = $this->request->post();
        $now  = time();
        // 如果该商品已有售后单
        if (isset($goods['refund']) && !empty($goods['refund'])) {
            $refund = $goods['refund']; // 一般就是一条

            // 仅当“已取消(status=30)”时允许重新申请；其他状态直接拦截
            if (isset($refund['status']['value']) ? (int)$refund['status']['value'] === 30
                                                : (int)$refund['status'] === 30) {

                // 重新开启这条售后单：重置流程字段、覆盖本次申请内容
                $data = [
                    'type'         => isset($post['type']) ? (int)$post['type'] : $refund['type'],
                    'apply_desc'   => isset($post['content']) ? trim($post['content']) : '',
                    'is_agree'     => 0,                // 0待审核
                    'refuse_desc'  => '',
                    'refund_money' => 0,
                    'is_user_send' => 0,
                    'send_time'    => 0,
                    'express_id'   => '',
                    'express_no'   => '',
                    'is_receipt'   => 0,
                    'status'       => 0,                // 0进行中
                    // 重新申请的时间你有两种选择：
                    // 1) 沿用旧的 create_time：注释下一行
                    // 2) 重新打上申请时间（更符合业务）：取消下一行注释
                    'create_time'  => $now,
                    'update_time'  => $now,
                ];

                Db::startTrans();
                try {
                    Db::name('order_refund')
                        ->where('order_refund_id', (int)$refund['order_refund_id'])
                        ->update($data);
                    DB::name('order_refund_image')
                        ->where('order_refund_id', (int)$refund['order_refund_id'])
                        ->delete();
                    // 重新插入图片
                    $post['images'] = explode(',', $post['images']);
                    if (isset($post['images']) && !empty($post['images'])) {
                        $images = [];
                        foreach ($post['images'] as $image) {
                            $images[] = [
                                'order_refund_id' => (int)$refund['order_refund_id'],
                                'image_id'           => $image,
                                'create_time'     => $now,
                                'wxapp_id'     => 10001,
                            ];
                        }
                        Db::name('order_refund_image')->insertAll($images);
                    }
                    // 如果你有“订单商品/订单”的售后状态标记，也可在这里一并恢复
                    // Db::name('yoshop_order_goods')->where('order_goods_id', $order_goods_id)
                    //   ->update(['refund_status' => 10]); // 示例：10=申请中

                    Db::commit();
                    return $this->renderSuccess([], '重新提交成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->renderError('提交失败：' . $e->getMessage());
                }
            }

            // 不是“已取消”的情况，一律视为已存在进行中/已处理的售后
            return $this->renderError('该商品已申请过售后');
        }

        // 首次申请：走你原有逻辑
        if ($model->apply($this->user, $goods, $post)) {
            return $this->renderSuccess([], '提交成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }
    public function qxapply($order_refund_id)
    {
        $model = new OrderRefundModel;
        $arr = $model->where("order_refund_id",$order_refund_id)->find();
        if($arr['status']['value']!=0){
            return $this->renderError('当前售后单不可取消');
        }
        if ($model->where("order_refund_id",$order_refund_id)->update(['status'=>30])) {
            return $this->renderSuccess();
        }else{
            return $this->renderError($model->getError() ?: '提交失败');
        }
    }
    /**
     * 售后单详情
     * @param $order_refund_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function detail($order_refund_id)
    {
        // 售后单详情
        $detail = OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if (empty($detail)) {
            return $this->renderError('售后单不存在');
        }
        // 物流公司列表
        $expressList = ExpressModel::getAll();
        return $this->renderSuccess(compact('detail', 'expressList'));
    }

    /**
     * 用户发货
     * @param $order_refund_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delivery($order_refund_id)
    {
        // 售后单详情
        $model = OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if ($model->delivery($this->postData())) {
            return $this->renderSuccess([], '操作成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }

}